package com.bbkb.quartz.shiro;

import com.bbkb.common.constants.ShiroConstant;
import com.bbkb.user.dto.SysUserDTO;
import com.bbkb.user.remoting.ISysUserRemoting;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class RememberMeFilter extends FormAuthenticationFilter {


    @Autowired
    private ISysUserRemoting sysUserRemoting;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated() && subject.isRemembered() && subject.getSession().getAttribute(ShiroConstant.SESSION_USER) == null) {
            Object principal = subject.getPrincipal();
            if (principal != null) {
                String userName = (String) principal;
                SysUserDTO sysUser = sysUserRemoting.getByUserName(userName);
                subject.getSession().setAttribute(ShiroConstant.SESSION_USER, sysUser);
            }
        }
        return subject.isAuthenticated() || subject.isRemembered();
    }
}
